//
//  AccountUserinfoVC.m
//  ImGuider
//
//  Created by llt on 2017/5/12.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "AccountUserinfoVC.h"
#import <IQKeyboardManager.h>

#import "TZImagePickerController.h"
#import "TZImageManager.h"

@interface AccountUserinfoVC () <UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, TZImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *label1;
@property (weak, nonatomic) IBOutlet UILabel *label2;
@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;

@property (nonatomic, strong) UIImagePickerController *imagePickerVC;

@end

@implementation AccountUserinfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (UIImagePickerController *)imagePickerVC {
    
    if (_imagePickerVC == nil) {
        _imagePickerVC = [[UIImagePickerController alloc] init];
        _imagePickerVC.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVC.navigationBar.barTintColor = kThemeColor;
        _imagePickerVC.navigationBar.tintColor = [UIColor whiteColor];
        _imagePickerVC.allowsEditing = YES;
    }
    return _imagePickerVC;
}

- (void)setup {
    
    self.title = MYLocalizedString(@"MYINFO_TITLE", nil);
    
    self.label1.text = MYLocalizedString(@"MYINFO_CHNAGEHEADER", nil);
    self.label2.text = MYLocalizedString(@"MYINFO_USERNAME", nil);
    self.tableView.backgroundColor = kBGColor;
    [self reloadTB];
}

- (void)reloadTB {
    
    self.headImageView.layer.borderWidth = 0.5f;
    self.headImageView.layer.borderColor = kContentColor.CGColor;
    self.headImageView.clipsToBounds = YES;
    self.headImageView.contentMode = UIViewContentModeScaleAspectFill;
    
    [self.headImageView setImageURL:[NSURL URLWithString:[UserManager sharedManager].user.headimg] placeholderImage:[UIImage imageNamed:@"default"]];
    self.nameLabel.text = [UserManager sharedManager].user.realname;
}

#pragma mark -UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row == 0) {// 修改头像
        
        
        
        UIAlertController *chooseImageAlert = [UIAlertController alertControllerWithTitle:nil message:MYLocalizedString(@"MYINFO_SELECT_PHOTO", nil) preferredStyle:UIAlertControllerStyleActionSheet];
        
        [chooseImageAlert addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) style:UIAlertActionStyleCancel handler:nil]];
        [chooseImageAlert addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"MYINFO_CAMERA", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self pushImagePickerController];
        }]];
        
        [chooseImageAlert addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"MYINFO_PHOTO", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self pushTZImagePickerController];
            
        }]];
        [self presentViewController:chooseImageAlert animated:YES completion:nil];
        
        
//        UIAlertController *chooseImageAlert = [UIAlertController alertControllerWithTitle:nil message:MYLocalizedString(@"MYINFO_SELECT_PHOTO", nil) preferredStyle:UIAlertControllerStyleActionSheet];
//        
//        [chooseImageAlert addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) style:UIAlertActionStyleCancel handler:nil]];
//        [chooseImageAlert addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"MYINFO_CAMERA", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            
//            UIImagePickerController *imagePick = [[UIImagePickerController alloc] init];
//            
//            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
//                imagePick.sourceType = UIImagePickerControllerSourceTypeCamera;
//            } else {
//                [IGUtils showToast:MYLocalizedString(@"PUBLIC_SYSTEM_ERROR", nil)];
//                return;
//            }
//            imagePick.delegate = self;
//            imagePick.allowsEditing = YES;
//            
//            self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
//            [self presentViewController:imagePick animated:YES completion:nil];
//            
//        }]];
//        [chooseImageAlert addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"MYINFO_PHOTO", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            
//            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
//            imagePicker.delegate = self;
//            imagePicker.allowsEditing = YES;
//            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//            [self presentViewController:imagePicker animated:YES completion:nil];
//            
////            UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kNavigationBarHeight)];
////            navView.backgroundColor = kThemeRedColor;
////
////            NSInteger index = imagePicker.view.subviews.count - 1;
////
////            [imagePicker.view insertSubview:navView atIndex:index > 0 ? index : 0];
//            
//            [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"nav_bg"] forBarMetrics:UIBarMetricsDefault];
//            [[UINavigationBar appearance] setTranslucent:NO];
////            UINavigationBar *navBar = imagePicker.navigationController.navigationBar;
////            [imagePicker.navigationController.navigationBar setTintColor:[UIColor blackColor]];
//            
//        }]];
//        
//        [self presentViewController:chooseImageAlert animated:YES completion:nil];
        
    } else if (indexPath.row == 1) {// 修改用户名
        
        UIAlertController *changeUseNameAlert = [UIAlertController alertControllerWithTitle:nil message:MYLocalizedString(@"MYINFO_CHNAGENICK", nil) preferredStyle:UIAlertControllerStyleAlert];
        [changeUseNameAlert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            
            textField.placeholder = MYLocalizedString(@"MYINFO_INPUTNICK", nil);
            textField.returnKeyType = UIReturnKeyDone;//Done按钮
            [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        }];
        
        [changeUseNameAlert addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) style:UIAlertActionStyleCancel handler:nil]];
        [changeUseNameAlert addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"PUBLIC_CONFIRM", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            UITextField *userNameTF = changeUseNameAlert.textFields.firstObject;
            if ([IGUtils isStringLenght0:userNameTF.text]) {
//                [IGUtils showToast:MYLocalizedString(@"MYINFO_INPUTNICK", nil)];
                return;
            }
            [NetAPIManager updateUserinfo:userNameTF.text type:0 block:^(NSString *result, NSError *error) {
                
                if (!error) {
                    [UserManager sharedManager].user.realname = userNameTF.text;
                    [IGUtils showToast:result];
                    [self reloadTB];
                    [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshUserNotif object:nil];
                }
            }];
        }]];
        
        [self presentViewController:changeUseNameAlert animated:YES completion:nil];
    }
}


//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//    
//    if ([[[[UITextInputMode activeInputModes] firstObject] primaryLanguage] isEqualToString:@"emoji"]) {
//        
//        return NO;
//    }
//    
//    return YES;
//}
/*
// *第一种方法，简单粗暴
// */
//- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
//    if ([[[textView textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textView textInputMode] primaryLanguage]) {
//
//        return NO;
//    }
//
//    return YES;
//}


#define MAX_STARWORDS_LENGTH 16

-(void)textFieldDidChange:(UITextField *)textField {

    NSString *toBeString = textField.text;
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position) {
        
        if (toBeString.length > MAX_STARWORDS_LENGTH) {
            
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];
            if (rangeIndex.length == 1) {
                
                textField.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];
            } else  {
                
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

#pragma mark - TZImagePickerController

- (void)pushTZImagePickerController {

    TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    // imagePickerVC.navigationBar.translucent = NO;

    imagePickerVC.allowTakePicture = NO; // 在内部显示拍照按钮
    
    // imagePickerVC.photoWidth = 1000;
    
    // 2. Set the appearance
    // 2. 在这里设置imagePickerVC的外观
    // imagePickerVC.navigationBar.barTintColor = [UIColor greenColor];
    // imagePickerVC.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    // imagePickerVC.oKButtonTitleColorNormal = [UIColor greenColor];
    // imagePickerVC.navigationBar.translucent = NO;
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVC.allowPickingVideo = NO;
    imagePickerVC.allowPickingImage = YES;
    imagePickerVC.allowPickingOriginalPhoto = YES;
    imagePickerVC.allowPickingGif = NO;
    imagePickerVC.allowPickingMultipleVideo = NO; // 是否可以多选视频
    
    /// 5. 单选模式,maxImagesCount为1时才生效
    imagePickerVC.showSelectBtn = NO;
    imagePickerVC.allowCrop = YES;
    imagePickerVC.needCircleCrop = NO;
    
    imagePickerVC.isStatusBarDefault = NO;
    
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
    }];
    
    [self presentViewController:imagePickerVC animated:YES completion:nil];
}

// 调用相机
- (void)pushImagePickerController {
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVC.sourceType = sourceType;
        if(iOS8Later) {
            _imagePickerVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        }
        [self presentViewController:_imagePickerVC animated:YES completion:nil];
    } else {
        IGLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        
        TZImagePickerController *tzimagePickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        
        
        [tzimagePickerVC showProgressHUD];
        UIImage* originalImg = [info objectForKey:UIImagePickerControllerOriginalImage];
        
       
        [NetAPIManager updateUserinfo:originalImg type:1 block:^(NSString *result, NSError *error) {
            if (!error) {
                //            [UserManager sharedManager].userName = userNameTF.text;
                [IGUtils showToast:MYLocalizedString(@"PUBLIC_MODIFY_SUCCESS", nil)];
                [self reloadTB];
                [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshUserNotif object:nil];
            }
        }];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - TZImagePickerControllerDelegate

/// User click cancel button
/// 用户点击了取消
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    // IGLog(@"cancel");
}

// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    UIImage *image = [photos firstObject];
    
    if (!image || ![image isKindOfClass:[UIImage class]]) {
        return;
    }
    
    [NetAPIManager updateUserinfo:image type:1 block:^(NSString *result, NSError *error) {
        
        if (!error) {
            [IGUtils showToast:MYLocalizedString(@"PUBLIC_MODIFY_SUCCESS", nil)];
            [self reloadTB];
            [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshUserNotif object:nil];
        }
    }];
}

// Decide album show or not't
// 决定相册显示与否
- (BOOL)isAlbumCanSelect:(NSString *)albumName result:(id)result {
    
    return YES;
}

// Decide asset show or not't
// 决定asset显示与否
- (BOOL)isAssetCanSelect:(id)asset {
    
    return YES;
}

@end
